package com.vaye.im.websocket;

import com.vaye.im.intercepter.PortalHandshakeInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.*;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * websocket配置类
 *
 * @author wangzhiyong
 * @module admin
 * @date 2023年01月19日 上午10:18
 */
@Configuration
@Slf4j
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Bean
    public ServerEndpointExporter serverEndpointConfig(){
        log.info("init serverEndpointConfig");
        return new ServerEndpointExporter();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(),"/ws").addInterceptors(new PortalHandshakeInterceptor());
    }

    public WebSocketHandler myHandler(){
        // 实现自定义的WebSocketHandler
        return new CustomWebSocketHandler();
    }

    class CustomWebSocketHandler implements WebSocketHandler {
        // 实现WebSocketHandler的方法
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            log.info("开始建立连接,sessionId={}",session.getId());
            session.sendMessage(new TextMessage("success"));


        }

        @Override
        public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
            log.info("开始处理消息：sessionId={}",session.getId());
            String msg = "服务端回复：" + message.getPayload();
            session.sendMessage(new TextMessage(msg));
        }

        @Override
        public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
            log.info("客户端断开连接：sessionId={}",session.getId());
        }

        @Override
        public boolean supportsPartialMessages() {
            return false;
        }
    }
}
